#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
全局配置模块

该模块定义了框架的全局配置参数。
"""

import os
import yaml
from typing import Dict, Any, Optional


def load_constants() -> Dict[str, Any]:
    """加载常量配置"""
    constants_file = os.path.join(os.path.dirname(__file__), 'constants.yaml')
    if os.path.exists(constants_file):
        with open(constants_file, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    return {}

# 加载常量配置
CONSTANTS = load_constants()

"""
全局配置模块

该模块定义了框架的全局配置参数。
"""

import os
from typing import Dict, Any, Optional


class Config:
    """
    全局配置类
    """
    

    # 测试用例配置
    TEST_CASE_DIR: str = 'test_cases'
    
    # 报告配置
    REPORT_DIR: str = 'reports'
    REPORT_FORMAT: str = 'html'  # 可选: html, json, text
    
    # 日志配置
    LOG_LEVEL: str = 'INFO'  # 可选: DEBUG, INFO, WARNING, ERROR, CRITICAL
    LOG_DIR: str = 'logs'

    # 请求配置
    REQUEST_TIMEOUT: int = 30  # 请求超时时间（秒）
    VERIFY_SSL: bool = True  # 是否验证SSL证书
    
    # 环境变量配置
    ENVIRONMENTS: Dict[str, Dict[str, Any]] = {
        'dev': {
            'base_url': 'https://supplydataerpapi.development.platform.babybus.com',
            'headers': {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ${token}'
            },
            'variables': {}
        },
        'test': {
            'base_url': 'https://supplydataerpapi.development.platform.babybus.com',
            'headers': {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ${token}'
            },
            'variables': {}
        },
        'prod': {
            'base_url': 'https://api.example.com',
            'headers': {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ${token}'
            },
            'variables': {}
        }
    }
    
    # 当前环境
    CURRENT_ENV: str = 'dev'
    
    # Swagger文档配置
    SWAGGER_URL: Optional[str] = 'https://supplydataerpapi.development.platform.babybus.com/swagger/v0.0.1/swagger.json'
    SWAGGER_FILE: Optional[str] = 'swagger.json'
    
    # 模拟数据生成配置
    AUTO_GENERATE_MOCK_DATA: bool = True  # 是否自动生成模拟数据
    CONFIRM_MOCK_DATA: bool = True  # 是否需要用户确认模拟数据
    MOCK_DATA_DEPTH: int = 3  # 模拟数据生成的最大深度
    
    @classmethod
    def get_environment(cls) -> Dict[str, Any]:
        """
        获取当前环境配置
        
        Returns:
            当前环境配置字典
        """
        return cls.ENVIRONMENTS.get(cls.CURRENT_ENV, {})
    
    @classmethod
    def get_base_url(cls) -> str:
        """
        获取当前环境的基础URL
        
        Returns:
            基础URL
        """
        env = cls.get_environment()
        return env.get('base_url', '')
    
    @classmethod
    def get_headers(cls) -> Dict[str, str]:
        """
        获取当前环境的默认请求头
        
        Returns:
            默认请求头字典
        """
        env = cls.get_environment()
        headers = env.get('headers', {}).copy()  # 创建副本以避免修改原始数据
        
        # 替换 token 占位符
        if 'Authorization' in headers:
            token = cls.get_token()
            headers['Authorization'] = headers['Authorization'].replace('${token}', token)
        
        return headers
    
    @classmethod
    def get_token(cls) -> str:
        """
        获取认证令牌
        
        Returns:
            认证令牌字符串
        """
        # 按优先级依次从不同来源获取token
        token = os.getenv('API_TOKEN', '')  # 1. 环境变量
        if not token:
            token = cls.get_variables().get('token', '')  # 2. 环境配置变量
        if not token:
            token = CONSTANTS.get('DEFAULT_TOKEN', '')  # 3. 常量配置
        
        return token
    
    @classmethod
    def get_variables(cls) -> Dict[str, Any]:
        """
        获取当前环境的变量
        
        Returns:
            变量字典
        """
        env = cls.get_environment()
        return env.get('variables', {})
    
    @classmethod
    def from_dict(cls, config_dict: Dict[str, Any]) -> None:
        """
        从字典加载配置
        
        Args:
            config_dict: 配置字典
        """
        for key, value in config_dict.items():
            if hasattr(cls, key):
                setattr(cls, key, value)
    
    @classmethod
    def from_file(cls, config_file: str) -> None:
        """
        从文件加载配置
        
        Args:
            config_file: 配置文件路径
        """
        if not os.path.exists(config_file):
            raise FileNotFoundError(f"配置文件不存在: {config_file}")
            
        # 根据文件扩展名决定如何加载
        if config_file.endswith('.py'):
            # 从Python模块加载
            import importlib.util
            spec = importlib.util.spec_from_file_location("config_module", config_file)
            config_module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(config_module)
            
            # 获取所有大写属性
            config_dict = {key: value for key, value in config_module.__dict__.items() 
                          if key.isupper() and not key.startswith('_')}
            cls.from_dict(config_dict)
        elif config_file.endswith('.json'):
            # 从JSON文件加载
            import json
            with open(config_file, 'r', encoding='utf-8') as f:
                config_dict = json.load(f)
            cls.from_dict(config_dict)
        elif config_file.endswith(('.yaml', '.yml')):
            # 从YAML文件加载
            import yaml
            with open(config_file, 'r', encoding='utf-8') as f:
                config_dict = yaml.safe_load(f)
            cls.from_dict(config_dict)
        else:
            raise ValueError(f"不支持的配置文件格式: {config_file}")